import logging

from fastapi import APIRouter, Body, Query
from tortoise.expressions import Q

from app.controllers.user import user_controller
from app.models import Dept
from app.schemas.base import Success, PageResp
from app.schemas.users import *

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/pages", summary="查看用户列表")
async def pages(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    username: str = Query("", description="用户名称，用于搜索"),
    email: str = Query("", description="邮箱地址"),
    alias: str = Query("", description="姓名"),
    phone: str = Query("", description="手机号"),
    dept_id: int = Query(None, description="部门ID"),
):
    """
    用户列表
    """
    q = Q()
    if username:
        q &= Q(username__contains=username)
    if email:
        q &= Q(email__contains=email)
    if alias:
        q &= Q(alias__contains=alias)
    if phone:
        q &= Q(phone__contains=phone)
    if dept_id:
        dept = await Dept.get(id=dept_id)
        if dept and dept.parent_id:
            q &= Q(dept_id=dept_id)
    total, user_objs = await user_controller.list(page=page, page_size=page_size, search=q)
    data = [await obj.to_dict(m2m=True, exclude_fields=["password"]) for obj in user_objs]

    # 获取部门信息
    dept_ids = set(obj.dept_id for obj in user_objs)
    dept_list = await Dept.filter(id__in=dept_ids).only("id", "name")
    dept_dict = {dept.id: dept.name for dept in dept_list}
    for item in data:
        item["dept"] = dept_dict[item["dept_id"]]

    return PageResp(data=data, total=total, page=page, page_size=page_size)


@router.get("/{user_id}", summary="根据ID获取查看用户")
async def get_by_id(user_id: int):
    """
    根据ID获取查看用户
    """
    user_obj = await user_controller.get(id=user_id)

    user_dict = await user_obj.to_dict(exclude_fields=["password"])
    user_dict["role_ids"] = [role.id for role in await user_obj.roles]

    return Success(data=user_dict)


@router.post("/", summary="创建用户")
async def create(user_in: UserCreate):
    """
    创建用户
    """
    new_user = await user_controller.create_user(obj_in=user_in)
    await user_controller.update_roles(new_user, user_in.role_ids)
    return Success(msg="Created Successfully")


@router.put("/", summary="修改用户")
async def update(user_in: UserUpdate):
    """
    修改用户
    """
    user = await user_controller.update(id=user_in.id, obj_in=user_in)
    await user_controller.update_roles(user, user_in.role_ids)
    return Success(msg="Updated Successfully")


@router.delete("/{user_id}", summary="删除用户")
async def delete(user_id: int):
    """
    删除用户
    """
    await user_controller.delete_by_id(user_id)
    return Success(msg="Deleted Successfully")


@router.post("/reset_password", summary="重置密码")
async def reset_password(user_id: int = Body(..., description="用户ID", embed=True)):
    """
    重置密码
    """
    await user_controller.reset_password(user_id)
    return Success(msg="密码已重置为123456")
